<?php

namespace mpend\modules\shop\controllers;

use Yii;
use mpend\components\Controller;
use common\helpers\ArrayHelper;
use common\models\shop\ShopCart;
use mpend\modules\shop\models\StandardProductUnit;

/**
 * SPU相关接口
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class SpuController extends Controller {

    /**
     * SKU详情
     * @view view.php
     * @return mixed
     */
    public function actionView($id) {
        $product = StandardProductUnit::findOrFail($id);

        $skus = ArrayHelper::toArray($product->goods);
        $specs = ArrayHelper::toArray($product->activeSpecs);
        $prices = ArrayHelper::getColumn($skus, 'price', []);
        $tree = $this->formatTree($specs);

        $sku = [
            'tree' => $tree,
            'list' => $skus,
            'price' => $product->price,
            'stock_num' => 227,
            'collection_id' => $product->id,
            'collection_price' => $product->price,
            'none_sku' => false,
            'sold_num' => 0,
            'min_price' => min($prices),
            'max_price' => max($prices),
            'hide_stock' => false
        ];
        $initSku = [];
        if (!empty($skus)) {
            $initSku = array_shift($skus);
        }

        $cartNums = 0;
        if ($this->uid) {
            $cartNums = ShopCart::find()->where([
                'user_id' => $this->uid,
                'deleted_at' => 0,
            ])->sum('num');
        }

        return [
            'goodsinfo' => $product,
            'sku' => $sku,
            'goods_id' => $id,
            'quota' => 0,
            'is_virtual' => 0,
            'quota_used' => 0,
            'initialSku' => $initSku,
            'cartSkuCount' => $cartNums ?: '',
        ];
    }

    public function formatTree($specs) {
        $trees = [];
        foreach ($specs as $spec) {
            $id = ArrayHelper::remove($spec, 'id');
            $name = ArrayHelper::remove($spec, 'name');
            $imgUrl = ArrayHelper::remove($spec, 'imgUrl');
            $v = compact('id', 'name');
            if ($imgUrl) {
                $v['imgUrl'] = $imgUrl;
            }
            $kid = $spec['k_id'];
            if (!isset($trees[$kid])) {
                $trees[$kid] = $spec;
            }
            $trees[$kid]['v'][$id] = $v;
        }
        foreach ($trees as $key => $item) {
            $v = ArrayHelper::remove($item, 'v');
            $trees[$key]['v'] = array_values($v);
        }
        return array_values($trees);
    }

}
